package top.lingkang.authoritypro.config.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.util.StringUtils;
import top.lingkang.authoritypro.data.dto.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lingkang
 * @date 2021/12/18
 * 替换 LoginUrlAuthenticationEntryPoint
 */
public class CustomLoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        if (StringUtils.isEmpty(httpServletRequest.getContentType())) {
            // 重定向到登录
            new DefaultRedirectStrategy().sendRedirect(httpServletRequest, httpServletResponse, "/auth/login");
            return;
        }
        //让浏览器用utf8来解析返回的数据
        httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
        httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
        httpServletResponse.getWriter().write(
                JSON.toJSONString(new ResponseResult<>().fail(10, "您还未登录或者登录已经失效，请重新登录"))
        );
    }
}
